package edu.ynu.se.xiecheng.achitectureclass.controller;

import edu.ynu.se.xiecheng.achitectureclass.entity.Greenhouse;
import edu.ynu.se.xiecheng.achitectureclass.dao.GreenhouseRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.time.ZoneId;

@RestController
@RequestMapping("/api/greenhouses")
@RequiredArgsConstructor
public class GreenhouseController {
    private final GreenhouseRepository greenhouseRepository;

    /**
     * 将LocalDateTime转换为Date
     */
    private Date convertToDate(LocalDateTime dateToConvert) {
        return Date.from(dateToConvert.atZone(ZoneId.systemDefault()).toInstant());
    }

    @PostMapping
    public ResponseEntity<Greenhouse> createGreenhouse(@RequestBody Greenhouse greenhouse) {
        greenhouse.setCreateTime(convertToDate(LocalDateTime.now()));
        return ResponseEntity.ok(greenhouseRepository.save(greenhouse));
    }

    @GetMapping
    public ResponseEntity<List<Greenhouse>> getAllGreenhouses() {
        return ResponseEntity.ok(greenhouseRepository.findAll());
    }

    @GetMapping("/{id}")
    public ResponseEntity<Greenhouse> getGreenhouse(@PathVariable Long id) {
        return greenhouseRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    public ResponseEntity<Greenhouse> updateGreenhouse(@PathVariable Long id, @RequestBody Greenhouse greenhouse) {
        return greenhouseRepository.findById(id)
                .map(existingGreenhouse -> {
                    greenhouse.setId(id);
                    greenhouse.setCreateTime(existingGreenhouse.getCreateTime());
                    return ResponseEntity.ok(greenhouseRepository.save(greenhouse));
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteGreenhouse(@PathVariable Long id) {
        return greenhouseRepository.findById(id)
                .map(greenhouse -> {
                    greenhouseRepository.delete(greenhouse);
                    return ResponseEntity.ok().<Void>build();
                })
                .orElse(ResponseEntity.notFound().build());
    }
}